from werkzeug.exceptions import HTTPException
from flask import request, json

from app import constants


class APIException(HTTPException):
    code = 500
    status = 'error'
    message = 'sorry, we made a mistake..'
    data = None
    error_code = 999

    def __init__(self, status=None, message=None, data=None, code=None, headers=None):
        if code:
            self.code = code
        if status:
            self.status = status
        if message:
            self.message = message
        if data is not None:
            self.data = data
        super(APIException, self).__init__(message, None)

    def get_body(self, environ=None):
        body = dict(
            code=self.code,
            status=self.status,
            message=self.message,
            data=self.data,
            request=request.method + " " + self.get_url_no_param()
        )
        text = json.dumps(body)
        return text

    def get_headers(self, environ=None):
        return [('Content-Type', 'application/json'), ('Access-Control-Expose-Headers', 'Version'),
                ('Version', constants.VERSION)]

    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]
